package com.google.code.synchronized_player;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class SettingsActivity extends Activity {
	EditText editTextIp;
	EditText editTextPort;
	EditText editTextListenPort;
	EditText editTextSourceDirectory;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		editTextIp = (EditText) findViewById(R.id.ip_text);
		editTextPort = (EditText) findViewById(R.id.port_text);
		editTextListenPort = (EditText) findViewById(R.id.listen_port_text);
		editTextSourceDirectory = (EditText) findViewById(R.id.text);
		LoadPreferences();
	}

	public void savePreferences(View v) {
		SharedPreferences.Editor editor = getSharedPreferences("network", MODE_WORLD_READABLE).edit();
		editor.putString("SourceDirectory", editTextSourceDirectory.getText().toString());
		editor.putString("IP", editTextIp.getText().toString());
		editor.putInt("port", Integer.parseInt(editTextPort.getText().toString()));
		editor.putInt("listenPort", Integer.parseInt(editTextListenPort.getText().toString()));
		editor.commit();
		finish();
	}

	public void onBrowseButton(View v) {
    	startActivityForResult(new Intent(this.getApplicationContext(), SelectorActivity.class), 1);
	}
	
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	String s = data.getStringExtra("path");
    	if(!s.equals("")) {
    		editTextSourceDirectory.setText(s);
    	}
    }
	
	public void cancelSettings(View v) {
		finish();
	}
	
	private void LoadPreferences() {
		SharedPreferences sharedPreferences = getSharedPreferences("network", MODE_WORLD_READABLE);
		String strSourceDirectory = sharedPreferences.getString("SourceDirectory", "");
		String strSavedIp = sharedPreferences.getString("IP", "");
		int strSavedPort = sharedPreferences.getInt("port", 0);
		int strSavedListenPort = sharedPreferences.getInt("listenPort", 0);
		editTextSourceDirectory.setText(strSourceDirectory);
		editTextIp.setText(strSavedIp);
		editTextPort.setText(String.valueOf(strSavedPort));
		editTextListenPort.setText(String.valueOf(strSavedListenPort));
	}

	public void finish() {
		Intent returnIntent = new Intent();
		setResult(RESULT_OK, returnIntent);     
		super.finish();
	}
}